package com.itheima.system.controller;


import com.github.pagehelper.Page;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.system.pojo.User;
import com.itheima.system.service.UserService;
import com.itheima.system.utils.CookieUtil;
import com.itheima.system.utils.JwtUtil;
import com.itheima.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;


    /**
     * 查询全部用户
     * @return
     */
    @GetMapping
    public Result findAll(){
        try {
            List<User> userList = userService.findAll();
            return new Result(true, StatusCode.OK,"查询成功",userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
    }

    /**
     *删除用户
     * @param id
     * @return
     */
    @PutMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        try {
            userService.delete(id);
            return new Result(true,StatusCode.OK,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"删除失败");
        }
    }

    /**
     *修改密码
     * @param user
     * @param password
     * @return
     */
    @PutMapping("/updatepassword/{password}")
    public Result updatePassword(@RequestBody User user,@PathVariable String password){
        String word = MD5Util.inputPassToFormPass(password);
        user.setPassword(word);
        userService.updatePassword(user);
        return new Result(true,StatusCode.OK,"修改密码成功");
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result findPage(@PathVariable  int page, @PathVariable  int size){
        Page<User> pageList = userService.findPage(page, size);
        PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try {
            userService.add(user);
            return new Result(true,StatusCode.OK,"添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加失败");
        }
    }

    @PostMapping("/addUserAndRole")
    public Result addUserAndRole(@RequestBody User user,Long[] roleIds){
        userService.addUserAndRole(user,roleIds);
        return new Result(true,StatusCode.OK,"用户角色关联成功");
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletResponse response) {
        try {
            User loginUser = userService.findUserNameAndPassWord(user);

            //是否是第一次登录
            if ("0".equals(loginUser.getFirstlogin())) {
                userService.updatePassword(user);
                return new Result(true, StatusCode.OK, "用户修改成功");
            } else {
                Map<String,String> info = new HashMap<>();
                info.put("username",user.getUsername());
                String token =
                        JwtUtil.createJWT(UUID.randomUUID().toString(), user.getUsername(),
                                null);
                info.put("token",token);

                String jti = info.get("username");

                //存储jti到cookie中
                this.saveJtiToCookie(jti,response);

                redisTemplate.boundValueOps("token"+jti).set(token);


                return new Result(true, StatusCode.OK, "登录成功",info);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.LOGINERROR, "登录失败,用户名或者密码错误");
    }

    /**
     * 用户退出功能
     * @param request
     * @return
     */
    @GetMapping("/loginOut")
    public Result loginOut(HttpServletRequest request,HttpServletResponse response){
        try {
            //首先用Enumeration的对象来得到所有的session中的信息
            Enumeration<String> em = request.getSession().getAttributeNames();
            //使用循环遍历，执行 removeAttribute（）的session删除操作
            while(em.hasMoreElements()){
                request.getSession().removeAttribute(em.nextElement().toString());
            }

            Cookie[] cookies = request.getCookies();
            for (Cookie c : cookies) {
                if (c.getName().equals("uid")){
                    c.setPath("/");
                    c.setMaxAge(0);
                    response.addCookie(c);
                    break;
                }
            }

            //redisTemplate.delete("token");

            return new Result(true,StatusCode.OK,"用户退出成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.LOGINERROR,"用户退出失败");
    }



    private void saveJtiToCookie(String jti, HttpServletResponse response) {
        /*
         cookieMaxAge: -1  #浏览器关闭时cookie失效 cookie生命周期 以秒为单位
            * @param name     cookie名字  "uid"
            * @param value    cookie值     jti
            * @param maxAge   cookie生命周期 以秒为单位
         */
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }
}
